package com.mysafe.provision.service.provision;

import com.mysafe.provision.model.cycletype.CycleType;
import com.mysafe.provision.model.expense.Expense;
import com.mysafe.provision.model.intervaltype.IntervalType;
import com.mysafe.provision.model.provision.Provision;

public class ProvisionService implements IProvisionService {
	public Provision calculateProvision(Expense expense) {
		Provision provision = null;
		if (isValidExpense(expense)) {
			provision = new Provision();
			double expenseValue = expense.getValue().doubleValue();
			double provisionValue = 0.0D;
			double divisor = expense.getCycle().getIntervalValue()
					.doubleValue();
			Integer idIntervalType = expense.getCycle().getIntervalType()
					.getId();
			if (idIntervalType.equals(IntervalType.YEAR))
				divisor *= 12.0D;
			else if (idIntervalType.equals(IntervalType.DAY)) {
				divisor /= 30.0D;
			}
			provisionValue = expenseValue / divisor;
			provision.setValue(Double.valueOf(provisionValue));
		}
		return provision;
	}

	private boolean isValidExpense(Expense expense) {
		boolean valid = true;
		if (expense == null) {
			valid = false;
		} else {
			if (expense.getValue() == null)
				valid = false;
			else if (expense.getValue().doubleValue() <= 0.0D) {
				valid = false;
			}
			if (expense.getCycle() == null) {
				valid = false;
			} else {
				if (expense.getCycle().getCycleType() == null) {
					valid = false;
				} else {
					Integer idCycleType = expense.getCycle().getCycleType()
							.getId();
					if ((!idCycleType.equals(CycleType.FIXED))
							&& (!idCycleType.equals(CycleType.VARIED))) {
						valid = false;
					}
				}
				if (expense.getCycle().getIntervalType() == null) {
					valid = false;
				} else {
					boolean validIntervalType = false;
					Integer idIntervalType = expense.getCycle()
							.getIntervalType().getId();
					if (idIntervalType.equals(IntervalType.DAY))
						validIntervalType = true;
					else if (idIntervalType.equals(IntervalType.MONTH))
						validIntervalType = true;
					else if (idIntervalType.equals(IntervalType.YEAR)) {
						validIntervalType = true;
					}
					if (!validIntervalType)
						valid = false;
				}
				if (expense.getCycle().getIntervalValue() == null) {
					valid = false;
				}
			}
		}
		return valid;
	}
}